
#pragma once
#include "resource.h"
#include "AddinLib_i.h"
#include "HTMLWindowImpl.h"
#include "Config.h"

using namespace ATL;


class ATL_NO_VTABLE CHtmlWindow :
	public CComObjectRoot,
	public IDispatchImpl<IHtmlWindow, &__uuidof(IHtmlWindow), &LIBID_StatCloud9MsoAddin, /* wMajor = */ 1, /* wMinor = */ 0>
{
private:
	CHtmlWindowImpl *pWindow;
	CAxWindow axWindow;
	CComPtr<IAddin> pAddin;
	CComBSTR name;

public:
	CHtmlWindow()
	{
		AtlAxWinInit();
	}

	BEGIN_COM_MAP(CHtmlWindow)
		COM_INTERFACE_ENTRY(IHtmlWindow)
		COM_INTERFACE_ENTRY2(IDispatch, IHtmlWindow)
	END_COM_MAP()
	 
	DECLARE_PROTECT_FINAL_CONSTRUCT()

	HRESULT Init(IAddin *pAddin, HWND parentWindow, BSTR name, BSTR bookmark, BSTR title, int width, int height) {
		HRESULT hr;
		
		this->name = name;
		this->pAddin = pAddin;
		
		pWindow = new CHtmlWindowImpl();

		RECT rect;
		rect.left = 0;
		rect.top = 0; 
		rect.right = width;
		rect.bottom = height;
		HWND hwnd = pWindow->Create(parentWindow, &rect, title);
		if(hwnd == NULL)
			return E_FAIL;

		axWindow.Attach(hwnd);
		hr = axWindow.CreateControl(L"{8856F961-340A-11D0-A96B-00C04FD705A2}");

		hr = axWindow.SetExternalDispatch(static_cast<IDispatch*>(this));

		if(SUCCEEDED(hr))
			hr = Navigate(bookmark);

		return hr;
	}

	HRESULT Navigate(BSTR bookmark) {
		CConfigHelper config;
		CComBSTR url;
		config.GetAppUrl(&url);
		url.Append('#');
		url.Append(bookmark);

		
		HRESULT hr;
		CComPtr<IWebBrowser2> pBrowser;
			hr = axWindow.QueryControl(&pBrowser);

		if(SUCCEEDED(hr))
			hr = pBrowser->Navigate(url, NULL, NULL, NULL, NULL);

		return hr;
	}	

	HRESULT FinalConstruct()
	{
		return S_OK;
	}

	void FinalRelease()
	{
	}
public:

	STDMETHOD(get_Name)(BSTR *pName) {
		name.CopyTo(pName);
		return S_OK;
	}

	STDMETHOD(get_Addin)(IAddin **ppAddin) {
		*ppAddin = pAddin;
		(*ppAddin)->AddRef();
		return S_OK;
	}

	STDMETHOD(get_HTMLDocument)(IDispatch **ppDoc) {
		return E_NOTIMPL;
	}

	STDMETHOD(get_Visible)(VARIANT_BOOL * pVisible) {
		if(pWindow->IsWindowVisible()) {
			*pVisible = VARIANT_TRUE;
		} else {
			*pVisible = VARIANT_FALSE;
		}
		return S_OK;
	}

	STDMETHOD(put_Visible)(VARIANT_BOOL visible) {
		if(visible) {
			pWindow->ShowWindow(SW_SHOW);
		} else {
			pWindow->ShowWindow(SW_HIDE);
		}
		return S_OK;
	}
};